  window.getUrlParam = (name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.parent.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
  }

  window.getUrlParam2 = (name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
  }

  window.scratchConfig = {
    apiDomain: 'http://175.24.98.133:9090',
    teachDomain: "https://manager.1717youxue.com",
    ideDomain: "https://ide.1717youxue.com/scratch/",//"http://127.0.0.1/test/scratch/",
    shareDomain: "https://share.1717youxue.com/scratch_preview/share.html",
    workId: null,
    unitId: null,
    logo: {
      show: true
      , url: ""
      , handleClickLogo: () => {
        console.log('点击LOGO')
      }
    }, 
    menuBar: {
      color: 'hsla(215, 100%, 65%, 1)'
    }, 
    saveButton: {
      //show: (window.getUrlParam2("scene") == "view" || window.getUrlParam2("scene") == "getCode" && window.getUrlParam2("scene") != "startCode") ? false : true,
      show: (window.getUrlParam2("scene") == "view" || window.getUrlParam2("scene") != "getCode" && window.getUrlParam2("scene") != "startCode") ? false : true,
      buttonName: window.getUrlParam2("scene") != "startCode" &&  window.getUrlParam2("scene") != "getCode" ? "提交" : "保存",
      handleClick: () => {
        if (window.getUserInfo()) {
          let projectTitle = window.scratch.getProjectName();
          if ($.trim(projectTitle) == "") {
            $.messageTip.error({
        　　   message:"作品名称不能为空！",
              fadeInTimeOut : 0.3,   //滑入秒数
              contentTimeOut : 1.5,  //内容停留秒数
              fadeOutTimeOut : 0.3, ////滑出秒数
            });
          } else {
            if (window.getUrlParam2("scene") != "startCode" && window.getUrlParam2("scene") != "getCode") {
                window.saveWork(()=>{
                  $.messageTip.success({
                　　   message:"作品保存成功！",
                      fadeInTimeOut : 0.3,   //滑入秒数
                      contentTimeOut : 1.5,  //内容停留秒数
                      fadeOutTimeOut : 0.3, ////滑出秒数
                    });
                });
            } else {
                //保存课堂练习
                if (window.getUrlParam2("scene") == "startCode") {
                    window.uploadTeachingCode2();
                } else {
                    window.uploadTeachingCode3();
                }
            }
          }
        } else {
          $.messageTip.error({
      　　   message:"请先登录！",
            fadeInTimeOut : 0.3,   //滑入秒数
            contentTimeOut : 1.5,  //内容停留秒数
            fadeOutTimeOut : 0.3, ////滑出秒数
          });
        }
      }
    },
    shareButton: {
      show: false,//(window.getUrlParam2("scene") == "view" || window.getUrlParam2("scene") == "getCode" && window.getUrlParam2("scene") != "startCode") ? false : true,
      buttonName: (window.getUrlParam2("scene") != "startCode" && !window.getUrlParam2("unitId")) ? "保存&分享" : "提交",
      handleClick: () => {
        //点击分享按钮
        console.log('分享按钮');
        let projectTitle = window.scratch.getProjectName();

        if ($.trim(projectTitle) == "") {
            $.messageTip.error({
        　　   message:"作品名称不能为空！",
              fadeInTimeOut : 0.3,   //滑入秒数
              contentTimeOut : 1.5,  //内容停留秒数
              fadeOutTimeOut : 0.3, ////滑出秒数
            });
            return ;
        }

        if (window.getUserInfo()) {
          window.scratch.getProjectCover(cover => {
            $("#projectCover").html('<image src="'+cover+'" style="width:320px;height:260px;margin-top:17px;" />');
            $('#publish').modal('toggle');
            $("#projectTitle").html(window.scratch.getProjectName());
          }); 
        } else {
          $.messageTip.error({
      　　   message:"请先登录！",
            fadeInTimeOut : 0.3,   //滑入秒数
            contentTimeOut : 1.5,  //内容停留秒数
            fadeOutTimeOut : 0.3, ////滑出秒数
          });
        }
      }
    }, 
    profileButton: {
      show: (this.getUrlParam2("isCreate")||this.getUrlParam2("isLive")) ? true : false,
      buttonName: "保存",
      handleClick:()=>{
        //点击profile按钮
      //   console.log('我的作品按钮')
      //   if (window.getUserInfo()) {
      //     window.open(window.scratchConfig.teachDomain + "/account/center");
      //   } else {
      //     $.messageTip.error({
      // 　　   message:"请先登录！",
      //       fadeInTimeOut : 0.3,   //滑入秒数
      //       contentTimeOut : 1.5,  //内容停留秒数
      //       fadeOutTimeOut : 0.3, ////滑出秒数
      //     });
      //   }
        let isCreate = this.getUrlParam2("isCreate");
        let isLive = this.getUrlParam2("isLive");
        if (isCreate==1||isLive==1) {
          window.saveCreateFile();
        }
      }
    }, 
    handleVmInitialized: (vm) => {
      window.vm = vm
      console.log("VM初始化完毕")
    },
    handleProjectLoaded:() => {
      console.log("作品载入完毕")
    },
    handleDefaultProjectLoaded:() => {
      //默认作品加载完毕，一般在这里控制项目加载
      console.log('默认作品加载完毕');
      if (window.scratchConfig.workInfo) {
        setTimeout(() => {
          window.scratch.setProjectName(window.scratchConfig.workInfo.workName);
        }, 500)
      }

      if (window.scratchConfig.unitInfo) {
        setTimeout(() => {
          window.scratch.setProjectName(window.scratchConfig.unitInfo.unitName + "课后作业");
        }, 500)
      }

      if (window.getUrlParam2('unitName')) {
        setTimeout(() => {
          window.scratch.setProjectName(decodeURI(decodeURI(window.getUrlParam2('unitName'))));
        }, 500)
      }
    },
    onLoginClick:() => {
      console.log("点击登录");
      window.location.href = window.scratchConfig.teachDomain + "/user/login?goto=" + window.scratchConfig.ideDomain;
    },
    onLogoutClick:() => {
      console.log("点击登出");
      // let token = window.getUrlParam("token");
      // if (token) {
      //   $.ajax({
      //     url: window.scratchConfig.apiDomain + "/api/sys/logout",
      //     headers: {
      //       "X-Access-Token": token
      //     },
      //     type: "get",
      //     success: function (data) {
      //       $.messageTip.success({
      //     　　   message:"已退出登录！",
      //           fadeInTimeOut : 0.3,   //滑入秒数
      //           contentTimeOut : 1.5,  //内容停留秒数
      //           fadeOutTimeOut : 0.3 ////滑出秒数   
      //       },
      //       () => {
      //         window.location.href = 'http://' + window.scratchConfig.ideDomain;
      //       });
      //     },
      //     complete: function() {
      //       window.showLoading(0); 
      //     }
      //   });
      // }
    },
    //素材cdn，若使用官方素材库请删除本配置项
    assetCDN: 'https://cdn.1717youxue.com/static/site/scratch/assets',
    //默认作品地址，若不需要请删除本配置项
    defaultProjectURL: "https://cdn.1717youxue.com/static/site/scratch/projects/default.sb3",
    //默认作品名
    defaultProjectName: "Scratch作品",
    //登录用户数据
    userData: {nickname: "", avatar: "https://cdn.1717youxue.com/static/site/common/images/default_avatar.png"},
    //作品信息
    workInfo: null,
    //课程信息
    unitInfo: null
  }

  window.showLoading = (s) => {
    s == 1 ? $("#loading_modal").show() : $("#loading_modal").hide();
  }

  window.dataURItoBlob = (base64Data) => {
      var byteString;
      if(base64Data.split(',')[0].indexOf('base64') >= 0)
          byteString = atob(base64Data.split(',')[1]);
      else
          byteString = unescape(base64Data.split(',')[1]);
      var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
      var ia = new Uint8Array(byteString.length);
      for(var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], {
          type: mimeString
      });
  }

  //获取用户信息
  window.getUserInfo = () => {
    let token = window.getUrlParam("token");console.log(token)
    if (token) {
      $.ajax({
          async: false,
          url: window.scratchConfig.apiDomain + "/api/sys/userinfo",
          headers: {
            "X-Access-Token": token
          },
          type: "get",
          success: function (data) {
            console.log(data);
            let userData = data.result;
            userData['nickname'] = userData.realname;
            if (userData['avatar'] == "") {
              userData['avatar'] = "https://cdn.1717youxue.com/static/site/common/images/default_avatar.png";
            }
            window.scratchConfig.userData = userData;
        //     $.messageTip.success({
        // 　　   message:"登录成功！",
        //       fadeInTimeOut : 0.3,   //滑入秒数
        //       contentTimeOut : 1.5,  //内容停留秒数
        //       fadeOutTimeOut : 0.3, ////滑出秒数
        //     });
          },
          error: function () {
            window.scratchConfig.userData = null;
          }
      });
    }
    return window.scratchConfig.userData;
  }

  //上传文件
  window.uploadFile = (fileName, fileTag, filePath) => {
    var id = null;
    let token = window.getUrlParam("token");
    $.ajax({
      url: window.scratchConfig.apiDomain + '/api/system/sysFile/add',
      type: 'POST',
      dataType: 'json',
      contentType: 'application/json',
      async: false,
      beforeSend: function (request) {
        request.setRequestHeader('Authorization', token)
      },
      data: JSON.stringify({
        fileType: 2,
        fileName: fileName,
        filePath: filePath,
        fileLocation: 2,
        fileTag: fileTag
      }),
      success: function (res) {
        if (res.code==0) {
          id = res.data.id
        }
      },
      error: function () {
      },
      complete: function () {
      }
    })
    console.log(id);
    return id;
  }

  //保存创作作品
  window.saveCreateFile = ()=>{
    let projectTitle = window.scratch.getProjectName();
    if ($.trim(projectTitle) == "") {
      $.messageTip.error({
  　　   message:"作品名称不能为空！",
        fadeInTimeOut : 0.3,   //滑入秒数
        contentTimeOut : 1.5,  //内容停留秒数
        fadeOutTimeOut : 0.3, ////滑出秒数
      });
    } else {
      window.saveWork(()=>{
        $.messageTip.success({
      　　   message:"作品保存成功！",
            fadeInTimeOut : 0.3,   //滑入秒数
            contentTimeOut : 1.5,  //内容停留秒数
            fadeOutTimeOut : 0.3, ////滑出秒数
          });
      });
    }
  }

  //上传作业代码(新)
  window.uploadCode = (callback) => {
    let token = window.getUrlParam2("token");
    let isCreate = window.getUrlParam2("isCreate");
    var fd = new FormData();
    window.scratch.getProjectFile(file => {
      //TODO 获取到项目文件
      //console.log(file)
      fd.append('file', file, 'project.sb3');
      $.ajax({
          headers: {
            "Authorization": token
          },
          type: 'POST',
          url: window.scratchConfig.apiDomain + '/api/work/uploadCode',
          data: fd,
          processData: false,
          contentType: false
      }).done(function(data) {
          console.log(data);
          if (callback) callback(data);
      });
    });
  }

  //上传作业
  window.uploadWork = (projectKey, coverKey, projectTitle, callback) => {
    let token = window.getUrlParam("token");
    $.ajax({
      url: window.scratchConfig.apiDomain + '/api/teachingWork/submit',
      type: 'POST',
      dataType: 'json',
      contentType: 'application/json',
      beforeSend: function (request) {
        request.setRequestHeader('Authorization', token)
      },
      data: JSON.stringify({
        //courseId: window.scratchConfig.unitId,
        workCover: coverKey,
        workFile: projectKey,
        workName: projectTitle,
        id: window.scratchConfig.workId,
        workType: 2,
        workDesc: '',
        operateDesc: ''
      }),
      success: function (res) {
        console.log(res);
        //window.scratchConfig.workId = res.result.id;
        //if (callback) callback(res.data.id);
        if (callback) callback();
      },
      error: function () {
        
      },
      complete: function () {
        window.showLoading(0);
      }
    })
  }
  
  //获取作品信息
  window.getWorkInfo = (workId) => {
    var data = null;
    $.ajax({
      async: false,
      url: window.scratchConfig.apiDomain + '/api/teaching/teachingWork/studentWorkInfo',
      data: { workId: workId },
      success: function (res) {
        console.log(res);
        data = res.result;
      },
      error: function (e) {
      }
    })
    return data;
  }

  //保存作品
  window.saveWork = (callback) => {
    window.showLoading(1);
    window.scratch.getProjectCover(cover => {
      let image = window.dataURItoBlob(cover);
      //console.log(image);
      var fd = new FormData();
      fd.append('files', image, 'cover.jpg');
      //fd.append('data', image);
      let token = window.getUrlParam("token");

      window.scratch.getProjectFile(file => {
        //TODO 获取到项目文件
        //console.log(file)
        fd.append('files', file, 'project.sb3');
        $.ajax({
            headers: {
              "Authorization": token
            },
            type: 'POST',
            url: window.scratchConfig.apiDomain + '/api/teachingWork/uploadwork',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            console.log(data);
            let coverKey = window.uploadFile(data.data.cover, "学生创作封面", data.data.cover);
            let projectKey = window.uploadFile(data.data.file, "学生创作文件", data.data.file);
            let projectTitle = window.scratch.getProjectName();
            console.log(coverKey)
            console.log(projectKey)
            window.uploadWork(projectKey, coverKey, projectTitle, callback);
        });
      })
    })
  }

  //上传课堂练习(老师获取学生代码)
  window.uploadTeachingCode = () => {
    window.showLoading(1);
    var fd = new FormData();
    let token = window.getUrlParam("token");

    window.scratch.getProjectFile(file => {
      //TODO 获取到项目文件
      //console.log(file)
      fd.append('files', file, 'project.sb3');
      $.ajax({
          headers: {
            "X-Access-Token": token
          },
          type: 'POST',
          url: window.scratchConfig.apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/2',
          data: fd,
          processData: false,
          contentType: false
      }).done(function(data) {
          window.showLoading(0);
          console.log(data);
          window.parent.sendCodeToTeacher(data);
      });
    })
  }

  //学生保存代码
  window.uploadTeachingCode2 = () => {
    window.showLoading(1);
    var fd = new FormData();
    let token = window.getUrlParam("token");

    window.scratch.getProjectFile(file => {
      //TODO 获取到项目文件
      //console.log(file)
      fd.append('files', file, 'project.sb3');
      $.ajax({
          headers: {
            "X-Access-Token": token
          },
          type: 'POST',
          url: window.scratchConfig.apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/2',
          data: fd,
          processData: false,
          contentType: false
      }).done(function(data) {
          window.showLoading(0);
          console.log(data);
          window.parent.saveCode(data);
      });
    })
  }

  //老师帮学生修改代码
  window.uploadTeachingCode3 = () => {
    window.showLoading(1);
    var fd = new FormData();
    let token = window.getUrlParam("token");

    window.scratch.getProjectFile(file => {
      //TODO 获取到项目文件
      //console.log(file)
      fd.append('files', file, 'project.sb3');
      $.ajax({
          headers: {
            "X-Access-Token": token
          },
          type: 'POST',
          url: window.scratchConfig.apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/2',
          data: fd,
          processData: false,
          contentType: false
      }).done(function(data) {
          window.showLoading(0);
          console.log(data);
          window.parent.saveCode2(data);
      });
    })
  }

  //分享作品
  window.onShare = () => {
    if ($.trim($("#workDesc").val()) == "" || $.trim($("#operateDesc").val()) == "") {
      $.messageTip.error({
  　　   message:"请填写完整再分享！",
        fadeInTimeOut : 0.3,   //滑入秒数
        contentTimeOut : 1.5,  //内容停留秒数
        fadeOutTimeOut : 0.3, ////滑出秒数
      });
    } else {
      window.saveWork((id) => {
        var shareUrl = window.scratchConfig.shareDomain + "?workId=" + id;
        console.log(shareUrl);
        $('#publish').modal('toggle');
        window.createCode('shareQrCode', shareUrl); 
        $('#showQrcode').modal('toggle');
        $('#shareQrCode img:first').css("margin", "0 auto");
      });
    }
  }

  //获取课程作业信息
  window.getUnitInfo = (access_token, unitId) => {
    var rs = null;
    $.ajax({
      async: false,
      url: window.scratchConfig.apiDomain + '/api/teaching/teachingCourseUnit/getUnitWorkInfo',
      data: {
        unitId: unitId
      },
      beforeSend: function(request) {
        request.setRequestHeader('X-Access-Token', access_token)
      },
      success: function(res) {
        console.log(res);
        rs = res.result;
      },
      error: function(e) {
        if (e.responseJSON.status == 500) {}
      }
    });
    return rs;
  }

  //生成二维码
  window.createCode = (id, src) => {
    $('#' + id).html('')
    var qrcode = new QRCode(document.getElementById(id), {
      width: 300,
      height: 300
    })
    qrcode.makeCode(src)
  }

  //加载库文件
  window.loadLibs = () => {
    //加载库文件
    jQuery.ajax({
      url: "https://cdn.1717youxue.com/static/site/scratch/libs/lib.min5.js",
      dataType: "script",
      cache: true
    }).done(function() {
      console.log("加载库文件成功！");
      jQuery.ajax({
        url: "https://cdn.1717youxue.com/static/site/scratch/libs/chunks/gui.js",
        dataType: "script",
        cache: true
      }).done(function() {
        console.log("加载player文件成功！");
        window.showLoading(0);
      });
    });
  }

  $(document).ready(function(){ 
    $.ajaxSettings.async = false;
    let assetJSON = window.assetJSON;
    for (a in assetJSON) {
      $.getJSON("https://cdn.1717youxue.com/static/site/scratch/assets/json/" + a + ".json", function(data){
          window.assetJSON[a] = data;
      });
    }
    //window.showLoading(0); 
    $.ajaxSettings.async = true;

    let workId = window.getUrlParam("workId");
  
    if (workId) {
      let rs = window.getWorkInfo(workId);
      if (rs) {
        window.scratchConfig.workId = workId;
        window.scratchConfig.workInfo = rs;
        window.scratchConfig.defaultProjectURL = rs.workFileUrl;
      }
    }

    if (window.getUrlParam2("codeUrl")) {
        window.scratchConfig.defaultProjectURL = 'https://cdn.1717youxue.com/' + window.getUrlParam2("codeUrl");
    }

    // var userData = window.getUserInfo();
    // if (userData) {
    //   let unitId = window.getUrlParam("unitId"); 
    //   if (unitId) {
    //     var rs = window.getUnitInfo(window.getUrlParam("token"), unitId);
    //     if (rs) {
    //       window.scratchConfig.defaultProjectURL = rs.courseWork;
    //       window.scratchConfig.unitId = unitId;
    //       window.scratchConfig.unitInfo = rs;
    //     }
    //   }
    // }

    window.loadLibs();
  });